<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="生产基地" prop="deptId">
        <!--<el-select
          v-model="queryParams.deptId"
          placeholder="请选择类型"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>-->
        <el-select v-model="queryParams.deptId" placeholder="请选择基地">
          <el-option v-for="dict in factoryListOptions" :key="dict.deptId" :label="dict.name" :value="dict.deptId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="计划月份" prop="planDate">
        <!--<el-date-picker
          :editable="false"
          v-model="planDate"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="monthrange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>-->
        <el-date-picker clearable v-model="queryParams.planDate" type="month" value-format="yyyy-MM-dd" placeholder="选择计划月份">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['produce:planReport:export']">导出</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['produce:plan:import']"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="dialogTableVisible = true"
          >追加</el-button
        >
      </el-col>
-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange" max-height="550">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="品项编码" align="center" prop="code" />
      <!--<el-table-column label="计划编码" align="center" prop="code" />-->
      <el-table-column label="品项名称" align="center" prop="name" minWidth="150px"/>
      <el-table-column label="基地名称" align="center" prop="deptName" />
      <el-table-column label="计划月份" align="center" prop="planDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planDate, "{y}/{m}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划产量" align="center" prop="porducePlanNumTotal" />
      <el-table-column label="基本计划量" align="center" prop="jibenTotal" />
      <el-table-column label="追加计划量" align="center" prop="zhuijiaTotal" />
      <el-table-column label="实际生产量" align="center" prop="actualNum" />
      <!--<el-table-column label="工厂id" align="center" prop="deptId" />-->
      <!-- <el-table-column
        label="任务完成状态"
        align="center"
        prop="status"
        :formatter="statusFormat"
      />-->

      <!-- <el-table-column
        label="操作"
        align="center"
        min-width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['produce:plan:view']"
            >查看</el-button
          >
          &lt;!&ndash;<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
            v-hasPermi="['produce:plan:edit']"
            >修改</el-button
          >&ndash;&gt;
         &lt;!&ndash; <el-button
            v-if="scope.row.progress.replace('%','') == 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['produce:plan:remove']"
            >删除</el-button
          >&ndash;&gt;
        </template>
      </el-table-column>-->
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改生产计划对话框 -->
    <el-dialog v-myFullscreen :title="title" :visible.sync="open" width="900px" append-to-body v-myDialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="计划名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入计划名称" :disabled="openDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型" :disabled="openDisabled">
                <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划月份" prop="planDate">
              <el-date-picker :editable="false" clearable size="small" v-model="form.planDate" type="date" value-format="yyyy-MM-dd" placeholder="选择计划月份" :disabled="openDisabled">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进度" prop="progress">
              <el-input v-model="form.progress" placeholder="请输入进度" :disabled="openDisabled" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!openDisabled">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  listPlanReport,
  getPlan,
  delPlan,
  addPlan,
  updatePlan,
  listUseDetail,
  addOhterPlan,
  uploadPlan,
  getFactoryList,
} from "@/api/produce/plan/planReport";
import { getToken } from "@/utils/auth";

export default {
  name: "Plan",
  data() {
    return {
      //弹窗是否禁止编辑
      openDisabled: true,
      // 遮罩层
      loading: true,
      loading2: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      ccpType: null,
      // 总条数
      total: 0,
      total2: 0,
      // 生产计划表格数据
      planList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 耗材量弹窗
      open2: false,
      // 类型字典
      typeOptions: [],
      // 任务完成状态字典
      statusOptions: [],
      factoryListOptions: [],
      // 计划导入参数
      upload: {
        // 是否显示弹出层（计划导入）
        open: false,
        // 弹出层标题（计划导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/produce/plan/import",
      },
      planDate: [],
      myDate: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        name: null,
        type: null,
        planDateStrat: null,
        planDateEnd: null,
        status: null,
      },
      queryParams2: {
        pageNum: 1,
        pageSize: 10,
        planId: null,
        planDetailId: null,
      },
      // 表单参数
      form: {},
      form2: {},
      pDate: "",
      // 表单校验
      rules: {
        name: { validator: this.$rules.required("计划名称") },
        planDate: { validator: this.$rules.required("计划月份") },
        deptId: { validator: this.$rules.required("目标基地") },
      },
      list: [], //数据列表
      useDetailList: [],
      dialogTableVisible: false, //弹窗是否隐藏
    };
  },
  created() {
    this.getList();
    this.getFactoryList();
  },
  methods: {
    /** 查询生产计划列表 */
    getList() {
      this.loading = true;
      listPlanReport(this.queryParams).then((response) => {
        this.planList = response.rows;
        // console.log(this.planList);
        this.total = response.total;
        this.loading = false;
      });
    },
    getFactoryList() {
      getFactoryList().then((response) => {
        this.factoryListOptions = response.data;
      });
    },

    getList2() {
      this.loading2 = true;
      listUseDetail(this.queryParams2).then((response) => {
        this.useDetailList = response.rows;
        this.total2 = response.total;
        this.loading2 = false;
      });
    },
    // 类型字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 任务完成状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      /*this.form = {
        id: null,
        code: null,
        name: null,
        type: null,
        // planDate: [],
        progress: null,
        deptId: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        remark: null,
      };*/
      this.resetForm("form");
      this.planDate = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.planDate && this.planDate.length > 0) {
        this.queryParams.planDateStart = this.planDate[0];
        this.queryParams.planDateEnd = this.planDate[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.planDate = [];
      this.queryParams.planDateStart = null;
      this.queryParams.planDateEnd = null;
      this.handleQuery();
    },

    /** 搜索按钮操作 */
    handleQuery2() {
      this.queryParams2.pageNum = 1;
      this.getList2();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.openDisabled = false;
      this.open = true;
      this.title = "添加生产计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.openDisabled = false;
      const id = row.id || this.ids;
      getPlan(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改生产计划";
      });
    },
    /** 查看按钮 */
    handleView(row) {
      this.$router.push({
        path: "/produce/plan/planDetail",
        query: {
          planId: row.id,
          name: row.name,
          month: row.planDate,
          status: row.status,
          type: row.type,
        },
      });
    },

    useHandleView(row) {
      this.queryParams2.planId = row.id;
      this.open2 = true;
      this.title = "查看耗材";
      // });
      this.handleQuery2();
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updatePlan(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const rLoading = this.openLoading();
            addPlan(this.form)
              .then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                rLoading.close();
                this.getList();
              })
              .catch((error) => {
                rLoading.close();
              });
          }
        }
      });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "produce/planReport/export",
        {
          ...this.queryParams,
        },
        "品项台账" + this.parseTime(new Date()) + ".xlsx"
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "计划导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "produce/plan/importTemplate",
        {
          ...this.queryParams,
        },
        `plan_${new Date().getTime()}.xlsx`
      );
    },

    // 追加框事件---------------
    del(index) {
      //删除
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.list.splice(index, 1);
        })
        .catch(() => {});
    },
    dialogChange(event, scope) {
      //选择后续操作
      if (event.options instanceof Array == true) {
        this.list.splice(scope.$index, 1, ...event.options);
      } else {
        this.list[scope.$index].name = event.options.name;
        this.list[scope.$index].code = event.options.code;
        this.list[scope.$index].unit = event.options.unit;
      }
      this.list.push({});
      this.list.pop();
    },
    add() {
      //添加
      this.list.push({});
    },

    restForm2() {
      this.list = [];
      this.form2.name = null;
      this.form2.planDate = null;
      this.dialogTableVisible = false;
    },
  },
};
</script>
